package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 地址管理
 */
@RestController
@RequestMapping("addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 查询地址簿
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        List<AddressBook> list = addressBookService.list();
        return R.success(list);
    }

    /**
     * 根据id查询数据
     */
    @GetMapping("/{id}")
    public R<AddressBook> selectById(@PathVariable Long id) {
        AddressBook one = addressBookService.lambdaQuery()
                .eq(id != null, AddressBook::getId, id)
                .one();
        return R.success(one);
    }

    /**
     * 修改地址信息
     */
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook) {
        //调用修改方法
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }

    /**
     * 添加地址信息
     */
    @PostMapping
    public R<String> add(@RequestBody AddressBook addressBook, HttpSession session) {
        //从session域中获取用户id
        Long userID = (Long) session.getAttribute("user");
        //设置关联字段
        addressBook.setUserId(userID);
        //调用添加方法
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }

    /**
     * 修改默认地址
     */
    @PutMapping("/default")
    public R<String> updateByDefault(@RequestBody AddressBook addressBook) {
        //调用修改方法,将所有默认值都设置为0(不默认)
        addressBookService.lambdaUpdate().set(AddressBook::getIsDefault, 0).update();
        //再次调用修改方法
        addressBookService.lambdaUpdate()
                //判断id相等,根据id设置
                .eq(AddressBook::getId, addressBook.getId())
                //设置默认值为1
                .set(AddressBook::getIsDefault, 1).update();

        return R.success("修改默认地址成功");
    }

    /**
     * 删除地址
     */
    @DeleteMapping
    public R<String> delete(Long ids) {
        addressBookService.lambdaUpdate()
                .eq(AddressBook::getId, ids)
                .remove();
        return R.success("删除成功");
    }

    /**
     * 查询默认地址
     * @return
     */
    @GetMapping("/default")
    public R<AddressBook> selectByDefault() {
        AddressBook one = addressBookService.lambdaQuery()
                .eq(AddressBook::getIsDefault, 1).one();
        return R.success(one);
    }

}
